//
//  HMOauthViewController.swift
//  Weibo
//
//  Created by 米易雅克 on 16/4/13.
//  Copyright © 2016年 米易雅克. All rights reserved.
//

import UIKit
import SVProgressHUD
class HMOauthViewController: UIViewController {

//    在loadView里面不用设置frame
    override func loadView() {
        view = webView
//        设置代理
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = GlobalBgColor
        
        
        setupNaVigationBar()
//        HMPrint(oauthViewURL())
        
        let webViewUrl = oauthViewURL()
        let request = NSURLRequest(URL: webViewUrl)
        webView.loadRequest(request)
        
//        添加指示器
    
        SVProgressHUD.showWithStatus("正在加载.....")
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.None)
        
    }
    
    
// 拼接webView路径
    private func  oauthViewURL()->NSURL {
    
        let urlStr = OauthURL + "?client_id=" + client_id + "&redirect_uri="
        + redirect_uri
        
        
        return NSURL(string: urlStr)!
    
    }
    
//    设置导航栏左右按钮
    private func setupNaVigationBar () {
    
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(HMOauthViewController.oauthFill))
    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(HMOauthViewController.oauthclose))
    
    }
//MARK: 按钮点击事件
   @objc private func oauthFill() {
    // 使用webView执行js代码
    let js = "document.getElementById('userId').value = '2367757591@qq.com';document.getElementById('passwd').value = 'qq769086882'"
    webView.stringByEvaluatingJavaScriptFromString(js)
    
    
    }
   @objc private func oauthclose() {
    
    SVProgressHUD.dismiss()
    dismissViewControllerAnimated(true, completion: nil)
    
    }
    
    
//  MARK : 懒加载UIWebView
   private lazy var webView = UIWebView()
    
}





///MARK: UIWebView 代理方法
extension HMOauthViewController : UIWebViewDelegate {

// MARK: 判断webView加载什么数据
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlStr = request.URL?.absoluteString
        // 当如果是  http://www.baidu.com/ 开头的地址,我们自己来处理拦截不让他去加载,其他的地址放行
        // 点击取消按钮: http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        
        // 点击授权: http://www.baidu.com/?code=4e496956aa012e11299494637e9ca536
        
        let rightURL = urlStr!.hasPrefix(redirect_uri)
        if !rightURL {
            // 不是授权回调地址,让他加载
            return true
        }else{
            // 授权回调地址,点击的是取消或授权
            // 判断点击的是取消还是授权按钮, 如果?后面是code=开头就是授权按钮
            // query是get请求?后面的东西
        let query = request.URL?.query
            let codeStr = "code="
            // 判断query是否是code=开头
            if query!.hasPrefix(codeStr) {
             // 截取 code=4e496956aa012e11299494637e9ca536 里面code=后面的内容
                 // 截取字符串转成NSString
                
                let code = (query! as NSString).substringFromIndex(codeStr.characters.count)
                HMPrint("code\(code)")
          
                HMUserAccountViewModel.sharedInstance.loadAccessToken(code, loadAccessTokenCallback: { (error) in
                    if error != nil {
                    
                    SVProgressHUD.showErrorWithStatus("网络不给力")
//                    延时加载
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(Int64)(1*NSEC_PER_SEC)), dispatch_get_main_queue(), { 
                            self.oauthclose()
                        })
                        return
                    }
//                    成功
                    
                    HMPrint("加载AccessToken成功")
                    self.oauthclose()
                    
//                    跳转到欢迎界面
                    let controller = HMWelcomeViewController()
                    (UIApplication.sharedApplication().delegate as! AppDelegate).switchViewController(controller)
                })
            }else{
            
//            取消按钮
                HMPrint("取消按钮")
//                关闭控制器
                oauthclose()
            
            
            }
            return false
        }
        
    }
    
                
                
                ////    获取accessToken
//    //    "access_token" = "2.00v1vb4GNimhZC9d97a06459JAYFPD";
//
//    private func loadAccessToken(code: String){
//    
//        let urlStr = accessTokenURLString
//        // 2.参数，字典
//        let parameters = [
//            "client_id": client_id,
//            "client_secret": client_secret,
//            "grant_type": grant_type,
//            "code": code,
//            "redirect_uri": redirect_uri
//        ]
//
//        HMNetworkTool.sharedInstance.POST(urlStr, parameters: parameters, progress: nil, success: { (task, responseObjec) in
//            
//            HMPrint("accessToken请求成功\(responseObjec)")
//            // as: 表示类型转换
//            // as?: 有可能转成功,有可能转失败
//            // as!: 一定能转成成功,如果转换失败,直接挂了
//            let result = responseObjec as? [String : AnyObject]
//            
//            if let dict = result {
//            
//            let userAccount = HMUserAccount(dict: dict)
//            
//            HMPrint("字典转换成功\(userAccount)")
//            
//                let filePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/account.plist")
//                NSKeyedArchiver.archiveRootObject(userAccount, toFile: filePath)
//            }
//            
//            }) { (task, error) in
//         
//            HMPrint("accessToken请求失败\(error)")
//        }
//    
//    
//    }
    
    
//webview 加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }

//webview加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
//       HMPrint("error: \(error)")
        if error?.code == 102 {
            // 点击取消,加载被中断
 
            
            return
        }
        
        SVProgressHUD.showErrorWithStatus("网络不给力")
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.None)
    }
}
